package pers.li.utils;

import pers.li.model.VO.UserVO;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

public class PublicUtils {
    public static <T> T getObjectByRequest(Class<T> clazz, HttpServletRequest request) {
        try {
            T t = clazz.newInstance();
            Field[] declaredFields = clazz.getDeclaredFields();
            for (Field field : declaredFields) {
                String fieldName = field.getName();
                if (request.getParameter(fieldName) != null && !request.getParameter(fieldName).equals("")) {
                    StringBuffer methodName = new StringBuffer();
                    methodName.append("set");
                    methodName.append(fieldName.substring(0, 1).toUpperCase());
                    methodName.append(fieldName.substring(1));
                    Class<?> type = field.getType();
                    Method method = clazz.getMethod(methodName.toString(), type);
                    if (type.getName().equals("java.lang.String"))
                        method.invoke(t, request.getParameter(fieldName));
                    else {
                        Method valueOf = type.getMethod("valueOf", String.class);
                        Object invoke = valueOf.invoke(null, request.getParameter(fieldName));
                        method.invoke(t, invoke);
                    }
                }
            }
            return t;
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
        }

        return null;
    }

    public static Integer getLoginUserId(HttpServletRequest req) {
        Map<String, Object> login = (Map<String, Object>) req.getSession().getAttribute("login");
        UserVO user = (UserVO) login.get("user");
        return user.getUserId();
    }

    public static void responseJson(HttpServletResponse resp, Map<String, Object> data) {
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
            writer.print(JsonUtil.toJsonString(data));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
